﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Threading;

namespace Base.ModuleBase.Attachs
{
    public class TextboxEnterLostFocusAttach
    {
        #region Public 方法

        /// <summary>
        /// Returns the value of the IsEnterLostFocusProperty
        /// </summary>
        /// <param name="obj">The dependency-object whichs value should be returned</param>
        /// <returns>The value of the given property</returns>
        public static bool GetIsEnterLostFocus(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsEnterLostFocusProperty);
        }

        /// <summary>
        /// Sets the value of the IsEnterLostFocusProperty
        /// </summary>
        /// <param name="obj">The dependency-object whichs value should be set</param>
        /// <param name="value">The value which should be assigned to the IsEnterLostFocusProperty</param>
        public static void SetIsEnterLostFocus(DependencyObject obj, bool value)
        {
            obj.SetValue(IsEnterLostFocusProperty, value);
        }

        #endregion Public 方法

        /// <summary>
        /// 点击间隔时间，最低100ms
        /// </summary>
        public static readonly DependencyProperty IsEnterLostFocusProperty = DependencyProperty.RegisterAttached("IsEnterLostFocus",
            typeof(bool), typeof(TextboxEnterLostFocusAttach), new UIPropertyMetadata(false, OnIsEnterLostFocusChanged));

        /// <summary>
        /// 点击间隔时间改变
        /// property was changed
        /// </summary>
        /// <param name="sender">The sender (the UIElement)</param>
        /// <param name="e">Some additional information</param>
        public static void OnIsEnterLostFocusChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            if (sender is TextBoxBase element && e.NewValue is bool value)
            {
                if (value)
                {
                    element.KeyDown += element_KeyDown;
                }
                else
                {
                    element.KeyDown -= element_KeyDown;
                }
            }
        }

        private static void element_KeyDown(object sender, KeyEventArgs e)
        {
            if (sender is TextBoxBase element)
            {
                if (e.Key == Key.Enter)
                {
                    element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                }
            }
        }
    }
}
